package com.yzc.controller;

import com.yzc.Details.SecurityUser;
import com.yzc.util.JwtUtil;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.Valid;
import jakarta.validation.constraints.NotBlank;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.csrf.CsrfToken;
import org.springframework.security.web.csrf.DefaultCsrfToken;
import org.springframework.web.bind.annotation.*;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Slf4j
@RestController
@RequestMapping("/securityLogin")
@RequiredArgsConstructor
public class SecurityLoginController {

    private final AuthenticationManager authenticationManager;
    private final JwtUtil jwtUtil;
    private final RedisTemplate<String, String> redisTemplate;

    @PostMapping("/login")
    public ResponseEntity<SecurityLoginResponse> login(
            @Valid @RequestBody SecurityLoginRequest request) {

        Authentication authentication = authenticationManager.authenticate(
                new UsernamePasswordAuthenticationToken(request.getUsername(), request.getPassword())
        );

        // 直接获取 SysUser 实例
        SecurityUser securityUser = (SecurityUser) authentication.getPrincipal();
        log.info("用户 ID: {}", securityUser.getId());  // 检查用户 ID 是否变化

        // 生成 Token
        String token = jwtUtil.generateSecurityToken(securityUser);
        log.info("生成 Token: {}", token);  // 检查 Token 是否不同

        // 存储到 Redis（使用 SysUser 的 ID）
        String redisKey = String.format("user:token:%s", securityUser.getId());
        log.info("存储到 Redis 的键: {}", redisKey);

        redisTemplate.opsForValue().set(
                redisKey,
                token,
                jwtUtil.getExpirationMillis(),
                TimeUnit.MILLISECONDS
        );
        log.info("Token 存储完成");  // 确认存储操作执行

        return ResponseEntity.ok(new SecurityLoginResponse(token));
    }

    // 请求响应对象
    @Data
    public static class SecurityLoginRequest {
        @NotBlank(message = "用户名不能为空")
        private String username;
        @NotBlank(message = "密码不能为空")
        private String password;
    }

    @Data
    @AllArgsConstructor
    public static class SecurityLoginResponse {
        private String token;
    }
}